package com.klm.easymq.core.impl;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.klm.easymq.config.EasyMqProperties;
import com.klm.easymq.core.IdempotentHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * Caffeine幂等处理器实现
 * 使用本地缓存实现幂等控制
 */
@Slf4j
public class CaffeineIdempotentHandler implements IdempotentHandler {
    
    private final Cache<String, Boolean> cache;
    
    public CaffeineIdempotentHandler(EasyMqProperties.Caffeine caffeineConfig) {
        this.cache = Caffeine.newBuilder()
                .maximumSize(caffeineConfig.getMaximumSize())
                .expireAfterWrite(caffeineConfig.getExpireAfterWrite(), TimeUnit.SECONDS)
                .build();
        log.info("Initialized Caffeine idempotent handler with maxSize={}, expireAfterWrite={}s", 
                caffeineConfig.getMaximumSize(), caffeineConfig.getExpireAfterWrite());
    }
    
    @Override
    public boolean isProcessed(String key) {
        Boolean processed = cache.getIfPresent(key);
        boolean result = processed != null && processed;
        log.debug("Check idempotent key: {}, result: {}", key, result);
        return result;
    }
    
    @Override
    public boolean tryAcquire(String key) {
        // 检查是否已存在
        if (isProcessed(key)) {
            return false;
        }
        
        // 尝试标记为已处理
        cache.put(key, true);
        log.debug("Acquired idempotent key: {}", key);
        return true;
    }
    
    @Override
    public void markProcessed(String key, int expireSeconds) {
        cache.put(key, true);
        log.debug("Marked idempotent key as processed: {}, expireSeconds: {}", key, expireSeconds);
    }
    
    @Override
    public void remove(String key) {
        cache.invalidate(key);
        log.debug("Removed idempotent key: {}", key);
    }
    
    @Override
    public String getType() {
        return "caffeine";
    }
} 